<script setup lang="ts">
import { reactive, ref } from "@vue/reactivity";
import type { AxiosResponse } from 'axios';
import { loginCheck } from "../api/admin.ts"
import type { ILogin } from "../myTypes/index";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

// 定义登录的数据
const loginData = reactive<ILogin>({
  adminname: "",
  password: ""
})

const router = useRouter();

// 登录功能：
function onSubmit() {

  loginCheck(loginData)
    .then((res: AxiosResponse) => {
      if (res.data.code === "200") {
        // 登录成功：

        let checkedKeys = res.data.data.checkedkeys;
        //1、存储该用户的菜单级的权限
        if (checkedKeys.length == 0) {
          checkedKeys = ["1", "2", "2-1", "2-2", "3", "3-1", "3-2", "4", "4-1", "4-2", "5", "6"];
        }
        sessionStorage.setItem("checkedKeys", JSON.stringify(checkedKeys));

        // 存储token
        sessionStorage.setItem("token", res.data.data.token);
        // 存储该用户名的名字
        sessionStorage.setItem("username", res.data.data.adminname);

        ElMessage({
          type: "success",
          message: "登录成功",
          duration: 1000,
          onClose: function () {
            // 跳转到首页
            router.push("/Admin");
          }
        })
      } else if (res.data.code === "10005") {
        ElMessage({
          type: "info",
          message: "该用户未注册",
        })
      }
    })
}


const themes = ref("dark");

function changeTheme(val: string) {

  themes.value = val;

  document.documentElement.className = themes.value === "dark" ? "dark" : "";
}

</script>

<template>
  <div class="login-box">

    <el-form :model="loginData" class="form-box" ref="loginFormRef">


      <el-radio-group v-model="themes" @change="changeTheme">
        <el-radio label="light">亮色调</el-radio>
        <el-radio label="dark">暗色调</el-radio>
      </el-radio-group>

      <el-form-item>
        <el-input v-model="loginData.adminname" placeholder="用户名" />
      </el-form-item>

      <el-form-item>
        <el-input type="password" v-model="loginData.password" placeholder="用户密码" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<style scoped>
.login-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url(https://cas.1000phone.net/cas/images/login/bg.png) 50% no-repeat;
  background-size: cover;
  overflow: hidden;
  position: relative;
}

.form-box {
  width: 400px;
  height: 200px;
  background-color: #fff;
  border: 1px solid #ededed;
  padding: 20px;
}
</style>
